/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-08-22 13:59:24
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-10 10:00:00
 * @FilePath: \work-tool\my-dev-project\src\views\order\list.tsx
 * @Description: 订单列表页面
 */
import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, DatePicker, Space, Modal, Form, message, Popconfirm } from 'antd';
import { 
  SearchOutlined, 
  FilterOutlined, 
  DownloadOutlined, 
  ReloadOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  PlusOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { RangePickerProps } from 'antd/es/date-picker';

const { Option } = Select;
const { Search } = Input;
const { RangePicker } = DatePicker;

// 模拟订单数据
const mockOrders = [
  {
    id: 'ORD-20250901-001',
    customer: '张三',
    phone: '13800138001',
    status: 'pending',
    amount: 1299,
    paymentMethod: 'wechat',
    createTime: '2025-09-01 10:30:00',
    deliveryTime: '2025-09-03 14:20:00',
    address: '北京市朝阳区建国路88号'
  },
  {
    id: 'ORD-20250901-002',
    customer: '李四',
    phone: '13800138002',
    status: 'paid',
    amount: 899,
    paymentMethod: 'alipay',
    createTime: '2025-09-01 11:45:00',
    deliveryTime: '',
    address: '上海市浦东新区陆家嘴金融中心'
  },
  {
    id: 'ORD-20250902-001',
    customer: '王五',
    phone: '13800138003',
    status: 'delivered',
    amount: 2599,
    paymentMethod: 'credit_card',
    createTime: '2025-09-02 09:15:00',
    deliveryTime: '2025-09-04 10:30:00',
    address: '广州市天河区天河路385号'
  },
  {
    id: 'ORD-20250902-002',
    customer: '赵六',
    phone: '13800138004',
    status: 'cancelled',
    amount: 599,
    paymentMethod: 'wechat',
    createTime: '2025-09-02 16:20:00',
    deliveryTime: '',
    address: '深圳市南山区科技园'
  },
  {
    id: 'ORD-20250903-001',
    customer: '钱七',
    phone: '13800138005',
    status: 'paid',
    amount: 1799,
    paymentMethod: 'alipay',
    createTime: '2025-09-03 13:10:00',
    deliveryTime: '',
    address: '杭州市西湖区文三路'
  },
  {
    id: 'ORD-20250903-002',
    customer: '孙八',
    phone: '13800138006',
    status: 'processing',
    amount: 1099,
    paymentMethod: 'credit_card',
    createTime: '2025-09-03 15:30:00',
    deliveryTime: '',
    address: '成都市锦江区春熙路'
  },
  {
    id: 'ORD-20250904-001',
    customer: '周九',
    phone: '13800138007',
    status: 'delivered',
    amount: 3299,
    paymentMethod: 'wechat',
    createTime: '2025-09-04 10:00:00',
    deliveryTime: '2025-09-06 09:45:00',
    address: '武汉市江汉区江汉路'
  },
  {
    id: 'ORD-20250904-002',
    customer: '吴十',
    phone: '13800138008',
    status: 'returned',
    amount: 799,
    paymentMethod: 'alipay',
    createTime: '2025-09-04 14:20:00',
    deliveryTime: '2025-09-06 16:10:00',
    address: '重庆市渝中区解放碑'
  },
];

interface Order {
  id: string;
  customer: string;
  phone: string;
  status: string;
  amount: number;
  paymentMethod: string;
  createTime: string;
  deliveryTime: string;
  address: string;
}

const OrderList: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>(mockOrders);
  const [filteredOrders, setFilteredOrders] = useState<Order[]>(mockOrders);
  const [searchText, setSearchText] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [paymentFilter, setPaymentFilter] = useState<string>('');
  const [dateRange, setDateRange] = useState<[string, string]>(['', '']);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState<boolean>(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [isEditModalVisible, setIsEditModalVisible] = useState<boolean>(false);
  const [editingOrder, setEditingOrder] = useState<Order | null>(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);

  // 搜索和筛选
  const handleSearch = (value: string) => {
    setSearchText(value);
    filterOrders(value, statusFilter, paymentFilter, dateRange);
  };

  const handleStatusFilter = (value: string) => {
    setStatusFilter(value);
    filterOrders(searchText, value, paymentFilter, dateRange);
  };

  const handlePaymentFilter = (value: string) => {
    setPaymentFilter(value);
    filterOrders(searchText, statusFilter, value, dateRange);
  };

  const handleDateRangeChange: RangePickerProps['onChange'] = (_dates, dateStrings) => {
    const newDateRange: [string, string] = [dateStrings[0] || '', dateStrings[1] || ''];
    setDateRange(newDateRange);
    filterOrders(searchText, statusFilter, paymentFilter, newDateRange);
  };

  const filterOrders = (
    search: string,
    status: string,
    payment: string,
    dateRange: [string, string]
  ) => {
    let result = [...orders];

    // 搜索过滤
    if (search) {
      result = result.filter(order => 
        order.id.includes(search) || 
        order.customer.includes(search) || 
        order.phone.includes(search)
      );
    }

    // 状态过滤
    if (status) {
      result = result.filter(order => order.status === status);
    }

    // 支付方式过滤
    if (payment) {
      result = result.filter(order => order.paymentMethod === payment);
    }

    // 日期范围过滤
    if (dateRange[0] && dateRange[1]) {
      result = result.filter(order => {
        const orderDate = order.createTime.split(' ')[0];
        return orderDate >= dateRange[0] && orderDate <= dateRange[1];
      });
    }

    setFilteredOrders(result);
  };

  // 重置筛选条件
  const resetFilters = () => {
    setSearchText('');
    setStatusFilter('');
    setPaymentFilter('');
    setDateRange(['', '']);
    setFilteredOrders(orders);
    form.resetFields();
  };

  // 刷新数据
  const refreshData = () => {
    setLoading(true);
    // 模拟网络请求延迟
    setTimeout(() => {
      // 模拟数据刷新
      setOrders([...mockOrders]);
      setFilteredOrders([...mockOrders]);
      setLoading(false);
      message.success('数据刷新成功');
    }, 500);
  };

  // 导出数据
  const exportData = () => {
    message.success('数据导出成功');
    // 实际项目中这里会调用导出API
  };

  // 查看订单详情
  const viewOrderDetail = (order: Order) => {
    setSelectedOrder(order);
    setIsDetailModalVisible(true);
  };

  // 编辑订单
  const editOrder = (order: Order) => {
    setEditingOrder(order);
    form.setFieldsValue(order);
    setIsEditModalVisible(true);
  };

  // 删除订单
  const deleteOrder = (orderId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该订单吗？删除后将无法恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        setOrders(orders.filter(order => order.id !== orderId));
        setFilteredOrders(filteredOrders.filter(order => order.id !== orderId));
        message.success('订单删除成功');
      },
    });
  };

  // 处理编辑表单提交
  const handleEditSubmit = () => {
    form.validateFields()
      .then(values => {
        if (editingOrder) {
          const updatedOrders = orders.map(order => 
            order.id === editingOrder.id ? { ...order, ...values } : order
          );
          setOrders(updatedOrders);
          
          // 更新过滤后的列表
          const updatedFilteredOrders = filteredOrders.map(order => 
            order.id === editingOrder.id ? { ...order, ...values } : order
          );
          setFilteredOrders(updatedFilteredOrders);
          
          message.success('订单更新成功');
        }
        setIsEditModalVisible(false);
        form.resetFields();
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 格式化状态显示
  const formatStatus = (status: string) => {
    const statusMap = {
      'pending': { text: '待支付', color: 'orange' },
      'paid': { text: '已支付', color: 'blue' },
      'processing': { text: '处理中', color: 'purple' },
      'delivered': { text: '已发货', color: 'green' },
      'completed': { text: '已完成', color: 'cyan' },
      'cancelled': { text: '已取消', color: 'red' },
      'returned': { text: '已退货', color: 'magenta' }
    };
    const statusInfo = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 格式化支付方式显示
  const formatPaymentMethod = (method: string) => {
    const methodMap = {
      'wechat': '微信支付',
      'alipay': '支付宝',
      'credit_card': '信用卡',
      'cash': '现金'
    };
    return methodMap[method as keyof typeof methodMap] || method;
  };

  // 表格列配置
  const columns: ColumnsType<Order> = [
    {
      title: '订单编号',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '客户名称',
      dataIndex: 'customer',
      key: 'customer',
      ellipsis: true,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      ellipsis: true,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '待支付', value: 'pending' },
        { text: '已支付', value: 'paid' },
        { text: '处理中', value: 'processing' },
        { text: '已发货', value: 'delivered' },
        { text: '已完成', value: 'completed' },
        { text: '已取消', value: 'cancelled' },
        { text: '已退货', value: 'returned' },
      ],
      onFilter: (value: string, record) => record.status === value,
      render: formatStatus,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      sorter: (a, b) => a.amount - b.amount,
      render: (amount) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      filters: [
        { text: '微信支付', value: 'wechat' },
        { text: '支付宝', value: 'alipay' },
        { text: '信用卡', value: 'credit_card' },
        { text: '现金', value: 'cash' },
      ],
      onFilter: (value: string, record) => record.paymentMethod === value,
      render: formatPaymentMethod,
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: '发货时间',
      dataIndex: 'deliveryTime',
      key: 'deliveryTime',
      render: (time) => time || '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button size="small" icon={<EyeOutlined />} onClick={() => viewOrderDetail(record)}>
            查看
          </Button>
          <Button size="small" icon={<EditOutlined />} onClick={() => editOrder(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除该订单吗？"
            description="删除后将无法恢复"
            okText="确定"
            okType="danger"
            cancelText="取消"
            onConfirm={() => deleteOrder(record.id)}
          >
            <Button size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card 
        title="订单列表"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} loading={loading} onClick={refreshData}>
              刷新
            </Button>
            <Button icon={<DownloadOutlined />} onClick={exportData}>
              导出
            </Button>
            <Button type="primary" icon={<PlusOutlined />}>
              创建订单
            </Button>
          </Space>
        }
      >
        {/* 搜索和筛选区域 */}
        <div style={{ marginBottom: 16, padding: 16, background: '#fafafa', borderRadius: 4 }}>
          <Space wrap>
            <Search
              placeholder="搜索订单号/客户名/电话"
              allowClear
              enterButton={<SearchOutlined />}
              size="middle"
              style={{ width: 300 }}
              onSearch={handleSearch}
            />
            
            <Select
              placeholder="订单状态"
              allowClear
              style={{ width: 150 }}
              onChange={handleStatusFilter}
              value={statusFilter}
            >
              <Option value="">全部</Option>
              <Option value="pending">待支付</Option>
              <Option value="paid">已支付</Option>
              <Option value="processing">处理中</Option>
              <Option value="delivered">已发货</Option>
              <Option value="completed">已完成</Option>
              <Option value="cancelled">已取消</Option>
              <Option value="returned">已退货</Option>
            </Select>
            
            <Select
              placeholder="支付方式"
              allowClear
              style={{ width: 150 }}
              onChange={handlePaymentFilter}
              value={paymentFilter}
            >
              <Option value="">全部</Option>
              <Option value="wechat">微信支付</Option>
              <Option value="alipay">支付宝</Option>
              <Option value="credit_card">信用卡</Option>
              <Option value="cash">现金</Option>
            </Select>
            
            <RangePicker 
              placeholder={['开始日期', '结束日期']}
              style={{ width: 300 }}
              onChange={handleDateRangeChange}
            />
            
            <Button icon={<FilterOutlined />} onClick={resetFilters}>
              重置筛选
            </Button>
          </Space>
        </div>

        {/* 订单表格 */}
        <Table
          columns={columns}
          dataSource={filteredOrders}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1300 }}
          loading={loading}
        />
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        title="订单详情"
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={700}
      >
        {selectedOrder && (
          <div className="order-detail">
            <div className="detail-section">
              <h3>基本信息</h3>
              <Space direction="vertical" size="large" style={{ width: '100%' }}>
                <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                  <span><strong>订单编号：</strong>{selectedOrder.id}</span>
                  <span><strong>订单状态：</strong>{formatStatus(selectedOrder.status)}</span>
                </Space>
                <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                  <span><strong>客户名称：</strong>{selectedOrder.customer}</span>
                  <span><strong>联系电话：</strong>{selectedOrder.phone}</span>
                </Space>
                <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                  <span><strong>订单金额：</strong>¥{selectedOrder.amount.toFixed(2)}</span>
                  <span><strong>支付方式：</strong>{formatPaymentMethod(selectedOrder.paymentMethod)}</span>
                </Space>
                <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                  <span><strong>下单时间：</strong>{selectedOrder.createTime}</span>
                  <span><strong>发货时间：</strong>{selectedOrder.deliveryTime || '-'}</span>
                </Space>
              </Space>
            </div>
            
            <div className="detail-section">
              <h3>收货信息</h3>
              <p><strong>收货地址：</strong>{selectedOrder.address}</p>
            </div>
          </div>
        )}
      </Modal>

      {/* 编辑订单模态框 */}
      <Modal
        title="编辑订单"
        open={isEditModalVisible}
        onCancel={() => setIsEditModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Form.Item
            label="订单编号"
            name="id"
          >
            <Input disabled />
          </Form.Item>
          
          <Form.Item
            label="客户名称"
            name="customer"
            rules={[{ required: true, message: '请输入客户名称' }]}
          >
            <Input placeholder="请输入客户名称" />
          </Form.Item>
          
          <Form.Item
            label="联系电话"
            name="phone"
            rules={[
              { required: true, message: '请输入联系电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          
          <Form.Item
            label="订单状态"
            name="status"
            rules={[{ required: true, message: '请选择订单状态' }]}
          >
            <Select placeholder="请选择订单状态">
              <Option value="pending">待支付</Option>
              <Option value="paid">已支付</Option>
              <Option value="processing">处理中</Option>
              <Option value="delivered">已发货</Option>
              <Option value="completed">已完成</Option>
              <Option value="cancelled">已取消</Option>
              <Option value="returned">已退货</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            label="订单金额"
            name="amount"
            rules={[
              { required: true, message: '请输入订单金额' },
              { type: 'number', min: 0, message: '订单金额必须大于等于0' }
            ]}
          >
            <Input type="number" placeholder="请输入订单金额" min={0} />
          </Form.Item>
          
          <Form.Item
            label="支付方式"
            name="paymentMethod"
            rules={[{ required: true, message: '请选择支付方式' }]}
          >
            <Select placeholder="请选择支付方式">
              <Option value="wechat">微信支付</Option>
              <Option value="alipay">支付宝</Option>
              <Option value="credit_card">信用卡</Option>
              <Option value="cash">现金</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            label="收货地址"
            name="address"
            rules={[{ required: true, message: '请输入收货地址' }]}
          >
            <Input.TextArea rows={3} placeholder="请输入收货地址" />
          </Form.Item>
          
          <Form.Item style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setIsEditModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OrderList;
